package cx3k.dataaccess;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cx3k.scheduler.objects.Profile;

public class ProfileManager extends CX3KDatabaseManager<Profile> {
	
	/**
	 * Logger object to handle log information.
	 */
	private static Logger logger = Logger.getLogger(ProfileManager.class.getName());
	
	public Profile delete(int id){		
		Profile toDelete = load(id);
		super.delete(toDelete);
		
		return toDelete;
	}
	
	public Profile load(int id){
		
		Profile ret = null;
		
		Session session = super.getSession();
		Transaction tx = session.beginTransaction();
		
		List<?> results = session.createQuery("from Profile as profile where profile.profileId = " + id).list();
		
		if(results != null && results.size() >= 1){
			try{
				ret = (Profile) results.get(0);
			}catch(ClassCastException e){
				logger.error("Could not load a Profile from the database.", e);
			}
		}
		
		tx.commit();
		session.close();
		
		return ret;
	}
	
	@SuppressWarnings("unchecked")
	public List<Profile> loadAll(){
		
		List<Profile> results;
		
		Session session = super.getSession();
		Transaction tx = session.beginTransaction();
		
		try{
			results = (List<Profile>) session.createQuery("from Profile as profile").list();
		} catch(ClassCastException e){
			logger.error("Could not load a Profile from the database.", e);
			results = new ArrayList<Profile>();
		}
		
		tx.commit();
		session.close();
		
		return results;
	}

}
